package com.xiaouyudeguang.common.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.xiaouyudeguang.common.config.SmsConfig;
import com.xiaouyudeguang.common.dto.SmsDto;
import com.xiaouyudeguang.common.validate.SmsRequestValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SmsUtils {

    public static final String PRODUCT = "Dysmsapi";
    public static final String DOMAIN = "dysmsapi.aliyuncs.com";

    private static SmsConfig smsConfig;

    private static SmsRequestValidate smsRequestValidate;

    public SmsUtils(SmsConfig smsConfig, @Autowired(required = false) SmsRequestValidate smsRequestValidate) {
        SmsUtils.smsConfig = smsConfig;
        SmsUtils.smsRequestValidate = smsRequestValidate;
    }

    public static SendSmsResponse send(String tenantId, String appId, String templateCode, SmsDto smsDto) throws Exception {
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName(smsConfig.getSignName());
        request.setPhoneNumbers(smsDto.getPhone());
        request.setTemplateCode(templateCode);
        request.setTemplateParam(JsonObject.toJson(smsDto.getTemplateParam()));
        return send(tenantId, appId, request);
    }

    public static SendSmsResponse send(String tenantId, String appId, SendSmsRequest request) throws Exception {
        if (smsRequestValidate != null) {
            request = smsRequestValidate.preHandle(tenantId, appId, request);
        }
        if (smsConfig.getLocalDev()) {
            SendSmsResponse response = new SendSmsResponse();
            response.setCode("OK");
            return response;
        }
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        DefaultProfile profile = DefaultProfile.getProfile(smsConfig.getRegionId(), smsConfig.getAccessKeyId(), smsConfig.getAccessKeySecret());
        DefaultProfile.addEndpoint(smsConfig.getRegionId(), PRODUCT, DOMAIN);
        IAcsClient client = new DefaultAcsClient(profile);
        SendSmsResponse response = client.getAcsResponse(request);
        if (smsRequestValidate != null) {
            response = smsRequestValidate.postHandle(tenantId, appId, response);
        }
        log.info("短信发送状态.status = {}, data = {}", response.getCode(), response.getMessage());
        return response;
    }
}
